package net.wenku8.reader.view.common

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.cache.CacheHandler
import net.wenku8.reader.service.FileService
import net.wenku8.reader.ui.lite.cardImage
import net.wenku8.reader.ui.lite.onTap

@Composable
fun CacheImage(cacheHandler : CacheHandler,
               modifier: Modifier = Modifier,
               contentScale: ContentScale = ContentScale.Fit,
               defaultShowImage : Boolean = false,
               defaultImage : Int = 0,
               onTap : (cacheHandler : CacheHandler) -> Unit = {}){
    var cached by remember { mutableStateOf(false) }
    LaunchedEffect(Unit) {
        launch(Dispatchers.IO) {
            cached = cacheHandler.doCache()
        }
    }
    if (cached){
        Image(
            painter = FileService.imageAsPainter(cacheHandler.getFile())!!,
            contentDescription = null,
            contentScale = contentScale,
            modifier = modifier.onTap {
                onTap(cacheHandler)
            }
        )
    }else{
        Row(
            modifier = modifier
        ) {
            if (defaultShowImage && defaultImage > 0){
                Image(
                    painter = painterResource(id = defaultImage),
                    contentDescription = null,
                    modifier = Modifier.cardImage()
                )
            }
        }
    }
}